package com.smg.securitydemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
//@EnableWebSecurity//Spring项目总需要添加此注解，SpringBoot项目中不需要
public class WebSecurityConfig {
//    @Bean
//    public UserDetailsService userDetailsService() {
//        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
//        manager.createUser( //此行设置断点可以查看创建的user对象
//                User
//                        .withDefaultPasswordEncoder()
//                        .username("huan") //自定义用户名
//                        .password("password") //自定义密码
//                        .roles("USER") //自定义角色
//                        .build()
//        );
//        return manager;
//    }

//    @Bean
//    public UserDetailsService userDetailsService() {
//        DBUserDetailsManager2 manager = new DBUserDetailsManager2();
//        return manager;
//    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //authorizeRequests()：开启授权保护
        //anyRequest()：对所有请求开启授权保护
        //authenticated()：已认证请求会自动被授权
        http.authorizeRequests(authorize -> authorize
                        .requestMatchers("/user/list").hasAuthority("USER_LIST")
                        //具有USER_ADD权限的用户可以访问/user/add
                        .requestMatchers("/user/add").hasAuthority("USER_ADD")
                        .anyRequest().authenticated())
                .formLogin(form->{
                    form
                            .loginPage("/login").permitAll() //登录页面无需授权即可访问
                            .usernameParameter("username") //自定义表单用户名参数，默认是username
                            .passwordParameter("password") //自定义表单密码参数，默认是password
                            .failureUrl("/login?error") //登录失败的返回地址
                            .successHandler(new MyAuthenticationSuccessHandler())//认证成功后的处理
                            .failureHandler(new MyAuthenticationFailaurHandler())//认证失败的处理
                    ;
                });
    //表单授权方式
//                .httpBasic(withDefaults());//基本授权方式
//关闭csrf攻击防御
        http.csrf((csrf) -> {
            csrf.disable();
        });
        http.logout(logout -> {
            logout.logoutSuccessHandler(new MyLogoutSuccessHandler()); //注销成功时的处理
            //错误处理
            try {
                http.exceptionHandling(exception  -> {
                    exception.authenticationEntryPoint(new MyAuthenticationEntryPoint());//请求未认证的接口
                    exception.accessDeniedHandler(new MyAcessDeniedHandler());
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //跨域
            try {
                http.cors(withDefaults());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            //会话管理
            try {
                http.sessionManagement(session -> {
                    session
                            .maximumSessions(1)
                            .expiredSessionStrategy(new MySessionInformationExpiredStrategy());
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return http.build();
    }
//    @Bean
//    public UserDetailsService userDetailsService2() {
//        DBUserDetailsManager2 manager = new DBUserDetailsManager2();
//        return manager;
//    }
@Bean
public DBUserDetailsManager2 dbUserDetailsManager2() {
    // 创建DBUserDetailsManager2的实例，这里可能需要注入其他依赖，如JdbcTemplate等
    return new DBUserDetailsManager2();
}

}
